import { createRouter, createWebHashHistory, RouteRecordRaw, RouteLocationNormalized } from 'vue-router'
import { routes } from '@/router/routes'
import { tokenStore } from '@/store/userStore'
import { menuStore, lastRouteStore } from '@/store/menuStore'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { MenuData } from '@/data/MenuData'

NProgress.configure({ showSpinner: false })
const modules = import.meta.glob([
  "../views/**/**.vue",
  "../components/**/**.vue"
]);

/**
 * 初始化路由
 */
const router = createRouter({
  history: createWebHashHistory(),
  routes: routes
})

router.beforeEach(async (to) => {
  NProgress.start()
  let title = to.meta.title as string
  document.title = title ? title : 'tpshion-admin'

  addLastRouteData(to)

  if (!checkLogin() && to.name !== 'Login') {
    // 将用户重定向到登录页面
    return { name: 'Login' }
  }else if(menuStore().menuRouter.length <= 0){
    await handleMenu()
    router.replace(to.path)
  }
})

router.afterEach(() => {
  // 关闭进度条
  NProgress.done()
});

function checkLogin():boolean {
  const token = tokenStore().token
  return token && token.length > 0 ? true : false
}

async function handleMenu(){
  const menuData = menuStore()
  await menuData.initMenuData()
  const routerData = buildRouter(menuData.menuData)
  menuData.setMenuRouter(routerData)

  const layout = routes.find((item: RouteRecordRaw) => item.name == "Layout")!;
  menuData.menuRouter.forEach(i => {
    layout.children?.push(i)
  })

  router.addRoute(layout)
}

function buildRouter(data:MenuData[]):RouteRecordRaw[] {
  const routerData:RouteRecordRaw[] = []
  if(!data || data.length <= 0){
    return routerData
  }

  data.forEach(i => {
    const data:RouteRecordRaw = makeRouteData(i)
    if(i.children && i.children.length > 0){
      data.children = buildRouter(i.children)
    }
    routerData.push(data)
  })
  return routerData
}

function makeRouteData(data:MenuData):RouteRecordRaw{
  let component = data.type === 0 ? modules[`../views${data.component}`] : modules['../components/layout/TpParent.vue']
  return {
    name: data.name,
    path: data.path,
    component: component,
    meta: {
      id: data.id,
      menuName: data.menuName,
      parentId: data.parentId,
      title: data.title,
      type: data.type,
      icon: data.icon
    },
    children: []
  }
}

function addLastRouteData(to: RouteLocationNormalized){
  if(to.meta.type === 0){
    const lastRouteData = lastRouteStore()
    lastRouteData.setLastRouteData({
      name: to.name?.toString(),
      path: to.path,
      menuName: '' + to.meta.menuName
    })
  }
}

export default router